<template>
	<view class="content">
		<view class="page login">
			<!-- <image class="login__bg" alt="image" src="/static/login/login_bg.png"/> -->
			<div class="login__top">
				<image class="login__logo" alt="image" :src="`${$ImgBaseUrl}logo2.png`" />
				<view class="login__title">欢迎登录零付</view>
			</div>
			<view class="login__content">
				<view class="login__input">
					<view class="login__password" v-if="isPasswordLogin">
						<input label="账号" placeholder="请输入手机号/邮箱" :value="passwordInfo.account"
							@change="onAccountChange" />
						<input label="密码" placeholder="请输入密码" type="password" clearable :value="passwordInfo.password"
							@change="onPasswordChange" />
					</view>
					<view v-else>
						<view class="input-item">
							<view slot="label" class="input-label input-label-tel">
								<image class="input_code" alt="image" :src="`${$ImgBaseUrl}tel.png`" />
								<text>+86</text>
								<uni-icons type="down" size="20" style="margin-left: 11rpx"></uni-icons>
							</view>
							<input v-model="phone" placeholder="请输入手机号" type="number" @change="onPhoneInput"
								class="custom-input custom-input-tel" />
						</view>
						<view class="input-item inpt-item-code">
							<view class="input-item-left">
								<view class="input-label">
									<image class="input_code" alt="image" :src="`${$ImgBaseUrl}code.png`" />
								</view>
								<input class="custom-input" placeholder="请输入验证码" v-model="code" type="number"
									:maxlength="6" @change="onCodeInput" />
							</view>
							<button class="verify" :class="phone ? 'verify--active' : ''" aria-role="button"
								@click="handleCountdown" :disabled="disabled">{{ countdownText }}</button>
						</view>
					</view>
				</view>

				<view class="login__tips">
					<checkbox style="transform: scale(0.7); margin-top: -8px" @click="onCheckChange" color="#2F80ED"
						backgroundColor="#EEF5FF" bordercolor="#999999" activeBackgroundColor="#EEF5FF"
						activeBorderColor="#2F80ED" iconColor="#2F80ED" />
					<view class="checkbox-label">
						<view>
							我已阅读并同意
							<text class="blue_link">《服务条款》</text>
							<text class="blue_link">《零付APP基本功能隐私政策》</text>
							<text class="blue_link">《零付招行服务及个人信息处理规范》</text>
							，未注册的手机号将自动注册
						</view>
					</view>
				</view>

				<view class="login__button">
					<view class="button" :class="phone && code ? 'verify--active' : ''" @click="handleLogin">登录</view>
				</view>
				<view class="login__usepassword">使用账号密码登录</view>

				<view class="login__password--forget" v-if="isPasswordLogin">
					<text>忘记密码？</text>
					<t-link theme="primary" size="small">找回密码</t-link>
				</view>
			</view>

			<view class="login__others">
				<text class="login__others-label">- 其他登录方式 -</text>

				<view class="login__others-buttons">
					<!-- 已勾选条款时显示获取手机号按钮 -->
					<button v-if="radioValue" class="login-button" open-type="getPhoneNumber"
						@getphonenumber="handleWxLogin" lang="zh_CN">
						<image class="wx_button" :src="`${$ImgBaseUrl}wx.png`" />
					</button>
					<!-- 未勾选时显示普通按钮 -->
					<button v-else class="login-button" @click="handleWxLoginClick">
						<image class="wx_button" :src="`${$ImgBaseUrl}wx.png`" />
					</button>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		mapState,
		mapMutations,
		mapActions
	} from "vuex";
	import {
		phoneLogin,
		smsCode,
		userInfo,
		wxMobileLogin,
		wxAppLogin
	} from "@/api/user.js";
	import {
		setPhone
	} from "@/utils/encryptionUtil";
	import Log from "../../mp_ecard_sdk/constants/log";
	import {
		updateAsyncPosition
	} from '@/api/common.js'
	const COUNTDOWN = 60;
	export default {
		data() {
			return {
				countdown: COUNTDOWN,
				disabled: false,
				btnDisabled: false,
				radioValue: false,
				countdownText: "获取验证码",
				timer: null,
				phone: '',
				code: '',
				isPasswordLogin: false,
				passwordInfo: {
					account: "",
					password: ""
				},
				miniProgramCode: '',
				isWxLoginLoading: false, // 防止重复提交
				UpdateAsyncParams: {
					provinceCode: "",
					cityCode: "",
					areaCode: "",
					provinceLive: "",
					cityLive: "",
					areaLive: "",
					address: "",
					lat: "",
					lng: ""
				}
			};
		},
		onLoad(options) {
			console.log('options', options);
			// 如果已经登录，则直接跳转到首页
			if (this.hasLogin) {
				// 修复：直接使用校验后的路径跳转
				 const targetUrl = this.redirectUrl || '/pages/index/index';
				uni.redirectTo({
					url: targetUrl
				});
				return;
			}
			// 处理重定向参数（提前校验）
			if (options.redirect) {
				this.redirectUrl = this.validatePath(decodeURIComponent(options.redirect));
			}
		},
		computed: {
			...mapState(["hasLogin"])
		},
		mounted() {},
		methods: {
			...mapMutations(["setAccessToken", "setUserInfo", "login"]),

			// 新增：校验页面路径有效性
			validatePath(path) {
				if (!path) return null;
				// 1. 路径必须以"/"开头
				if (!path.startsWith('/')) {
					path = '/' + path;
				}
				// 2. 过滤非法字符（可选，根据业务需求）
				if (/[\\:*?"<>|]/.test(path)) {
					return null;
				}
				// 3. 校验是否为已注册页面（关键！需与app.json中注册的页面匹配）
				const validPages = [
					'/pages/index/index',
					'/pages/login/completeInformation',
					// 在此处添加所有合法页面路径，例如：
					// '/app/bus/sevItem/getSevItemList' // 如果该页面实际存在，需添加到这里
				];
				return validPages.includes(path) ? path : null;
			},

			handleSmsCode() {
				smsCode({
					phonenumber: this.phone
				}).then((res) => {
					if (res.code === 200) {
						uni.showToast({
							icon: "none",
							title: "验证码已发送成功，请注意查收！"
						});
					} else {
						uni.showToast({
							icon: "none",
							title: res.msg
						});
						this.reset();
					}
				});
			},


			// 微信登录按钮点击事件（用于触发登录流程）
			handleWxLoginClick() {
				// 可以在这里添加一些前置检查
				if (!this.radioValue) {
					uni.showToast({
						icon: 'none',
						title: '请先阅读并同意服务条款'
					});
					return;
				}
			},
			// 微信获取手机号回调，调整为先调 wxAppLogin 获取 openId，再调 wxMobileLogin
			async handleWxLogin(e) {

				if (!this.radioValue) {
					uni.showToast({
						icon: 'none',
						title: '请先阅读并同意服务条款'
					});
					return;
				}
				// 添加检查
				this.handleWxLoginClick()


				if (this.isWxLoginLoading) return;
				if (e.detail.errMsg !== 'getPhoneNumber:ok') {
					uni.showToast({
						icon: 'none',
						title: '您拒绝了手机号授权'
					});
					return;
				}

				this.isWxLoginLoading = true;
				uni.showLoading({
					title: '登录中...',
					mask: true
				});

				try {
					// 1. 获取微信临时登录凭证 code
					const loginRes = await this.getWxCode();
					console.log('loginRes', loginRes)
					if (!loginRes.code) {
						throw new Error('获取微信 code 失败');
					}

					// 2. 调用 wxAppLogin 获取 openId 或直接获取登录态
					const wxAppLoginRes = await wxAppLogin({
						code: loginRes.code
					});
					console.log('wxAppLoginRes', wxAppLoginRes)
					if (wxAppLoginRes.code !== 200) {
						throw new Error('调用 wxAppLogin 失败，' + wxAppLoginRes.msg);
					}

					// 判断 wxAppLoginRes 返回数据，若已有 access_token 等登录态数据，直接走登录成功逻辑
					if (wxAppLoginRes.data.access_token) {
						await this.handleLoginSuccess(wxAppLoginRes.data);
						return;
					}

					// 若返回 openId，则继续调用 wxMobileLogin
					const openId = wxAppLoginRes.data.openId;
					if (!openId) {
						throw new Error('wxAppLogin 返回数据中未获取到 openId');
					}

					// 3. 调用 wxMobileLogin 获取 token
					const wxMobileLoginRes = await wxMobileLogin({
						openId: openId,
						code: e.detail.code,
					});
					console.log('wxMobileLoginRes', wxMobileLoginRes)
					if (wxMobileLoginRes.code !== 200) {
						throw new Error('调用 wxMobileLogin 失败，' + wxMobileLoginRes.msg);
					}

					// 4. 处理登录成功逻辑
					await this.handleLoginSuccess(wxMobileLoginRes.data);

				} catch (error) {
					console.error('微信登录错误:', error);
					uni.showToast({
						icon: 'none',
						title: loginRes.msg || '微信登录失败'
					});
				} finally {
					this.isWxLoginLoading = false;
					uni.hideLoading();
				}
			},


			// 获取微信code
			getWxCode() {
				return new Promise((resolve, reject) => {
					wx.login({
						success: (res) => {
							if (res.code) {
								resolve(res);
							} else {
								reject('登录失败！' + res.errMsg);
							}
						},
						fail: (err) => {
							reject('登录调用失败！' + err.errMsg);
						}
					});
				});
			},

			async handleLoginSuccess(loginData) {
				this.setAccessToken(loginData.access_token ? `Bearer ${loginData.access_token}` : '');
				try {
					const userRes = await userInfo();
					if (userRes.code === 200) {
						uni.showToast({
							icon: 'success',
							title: '登录成功'
						});
						// 登录成功后调用位置更新方法
						this.getUpdateAsyncPosition();
						// userRes.data.phone = setPhone(userRes.data.phone);
						// this.setUserInfo(userRes.data);
						this.$store.commit('setUserInfo', {
							...userRes.data
						})

						uni.setStorageSync('user_info', userRes.data);
						this.login();
						// console.log('userRes.data', userRes.data);
						setTimeout(() => {
							if (userRes.data.isFirstLogin === '1') {
								// 首次登录固定跳转到完善信息页
								uni.redirectTo({
									url: "/pages/login/completeInformation"
								});
							} else {
								const targetUrl = this.redirectUrl || '/pages/index/index';
								uni.redirectTo({
									url: targetUrl
								});
							}
						}, 500);
					} else {
						throw new Error(userRes.msg || '获取用户信息失败');
					}
				} catch (error) {
					console.error('登录后处理失败:', error);
					uni.showToast({
						icon: 'none',
						title: '登录失败，请重试'
					});
				}
			},
			getUpdateAsyncPosition() {
				try {
					const locationStr = uni.getStorageSync('current_location');
					if (!locationStr) {
						console.warn('本地未存储位置信息，无法更新');
						return; // 无位置信息时不调用接口
					}
					const currentLocation = JSON.parse(locationStr);
					// 填充位置参数
					this.UpdateAsyncParams.provinceCode = currentLocation.provinceCode || '';
					this.UpdateAsyncParams.cityCode = currentLocation.cityCode || '';
					this.UpdateAsyncParams.areaCode = currentLocation.areaCode || '';
					this.UpdateAsyncParams.provinceLive = currentLocation.provinceName || '';
					this.UpdateAsyncParams.cityLive = currentLocation.cityName || '';
					this.UpdateAsyncParams.areaLive = currentLocation.areaName || '';
					this.UpdateAsyncParams.lat = currentLocation.latitude || '';
					this.UpdateAsyncParams.lng = currentLocation.longitude || '';
					this.UpdateAsyncParams.address = currentLocation.address || '';

					// 调用接口并处理结果
					updateAsyncPosition(this.UpdateAsyncParams)
						.then((res) => {
							// console.log('位置信息更新成功:', res);
							// 可根据接口返回结果添加成功逻辑（如提示）
						})
						.catch((err) => {
							console.error('位置信息更新失败:', err);
							// 失败时不阻断登录流程，仅打印日志
						});
				} catch (e) {
					console.error('解析位置信息失败:', e);
				}
			},

			onCheckChange(e) {
				this.radioValue = !this.radioValue;
			},
			handleLogin() {
				// uni.redirectTo({
				//   url: "/pages/login/completeInformation"
				// })
				this.verifyPhone(() => {
					if (!this.code) {
						uni.showToast({
							icon: "none",
							title: "请输入验证码"
						});
						return false;
					}
					if (!this.radioValue) {
						uni.showToast({
							icon: "none",
							title: "请先阅读并勾选服务条款"
						});
						return false;
					}
					// console.log("222");
					uni.showLoading({
						title: "提交中...",
						mask: true
					});
					uni.login({
						success: (loginInfo) => {
							phoneLogin({
									code: this.code,
									wxCode: loginInfo.code,
									mobile: this.phone
								})
								.then((res) => {
									if (res.code === 200) {
										this.setAccessToken(`Bearer ${res.data.access_token}`);
										userInfo().then((info) => {
											if (info.code === 200) {
												uni.showToast({
													icon: "success",
													title: "登录成功"
												});
												this.getUpdateAsyncPosition();
												this.$store.commit('setUserInfo', {
													...info.data
												});
												// 确保缓存完全写入后再跳转
												uni.setStorageSync('user_info', info.data);
												this.login();

												// 关键修改：使用setTimeout确保异步操作完成
												setTimeout(() => {
													if (info.data.isFirstLogin ===
														'1') {
														uni.redirectTo({
															url: "/pages/login/completeInformation"
														});
													} else {
														uni.redirectTo({
															url: "/pages/index/index"
														});
													}
												}, 500); // 延迟500ms确保缓存写入
											} else {
												uni.showToast({
													icon: "none",
													title: info.msg
												});
												this.reset();
											}
										});
									} else {
										uni.showToast({
											icon: "none",
											title: res.msg
										});
										this.reset();
									}
								})
								.finally(() => {
									this.reset();
									uni.hideLoading();
								});
						}
					});
				});
			},
			verifyPhone(callback) {
				if (!this.phone) {
					// uni.showToast({
					//   icon: "none",
					//   title: "请输入手机号码"
					// });
					return false;
				}
				if (!/^1[3-9]\d{9}$/.test(this.phone)) {
					uni.showToast({
						icon: "none",
						title: "手机号码有误，请重填"
					});
					return false;
				}
				callback();
			},
			handleCountdown() {
				this.verifyPhone(() => {
					this.disabled = true;
					this.handleSmsCode();
					this.timer = setInterval(() => {
						if (this.countdown <= 1) {
							this.countdown = COUNTDOWN;
							clearInterval(this.timer);
							this.disabled = false;
							this.countdownText = "获取验证码";
						} else {
							this.countdown--;
							this.countdownText = `${this.countdown}s`;
						}
					}, 1000);
				});
			},
			reset() {
				this.btnDisabled = false;
				if (this.timer) {
					this.countdown = COUNTDOWN;
					clearInterval(this.timer);
					this.disabled = false;
					this.countdownText = "获取验证码";
				}
			}
		},
		beforeDestroy() {
			this.reset();
		}
	};
</script>

<style lang="less">
	.login {
		background: linear-gradient(180deg, #cae1ff 0%, #eef5ff 100%);
		padding: 232rpx 0 30rpx;
		// height: calc(100vh - 56px);
		overflow-y: auto;

		// &__bg{
		//   width: 750rpx;
		//   height: 100vh;
		//   position: fixed;
		//   top: 0;
		//   z-index:-1;
		// }
		&__top {
			display: flex;
			flex-direction: column;
			align-items: center;
		}

		&__content {
			padding: 0 24rpx;
		}

		&__title {
			font-size: 48rpx;
			color: #333333;
			line-height: 67rpx;
			margin: 34rpx 0 60rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			text-align: center;
		}

		&__logo {
			width: 160rpx;
			height: 160rpx;
			color: rgba(0, 0, 0, 0.9);
		}

		&__input {
			.input-item {
				display: flex;
				align-items: center;
				box-sizing: border-box;
				height: 104rpx;
				background: #ffffff;
				border-radius: 52rpx;
				padding: 30rpx 24rpx 30rpx 40rpx;
				margin-bottom: 44rpx;
			}

			.input-item-left {
				display: flex;
				align-items: center;
				flex: 1;
			}

			.inpt-item-code {
				justify-content: space-between;
			}

			.input-label {
				display: flex;
				align-items: center;
				box-sizing: border-box;
			}

			.input-label-tel {
				width: 200rpx;
				display: flex;
				align-items: center;
				box-sizing: border-box;
			}

			.input-icon {
				margin-left: 8rpx;
			}
		}

		&__tips {
			display: flex;
			color: rgba(0, 0, 0, 0.4);
			font-size: 24rpx;
			font-style: normal;
			font-weight: 400;
			line-height: 40rpx;
			margin: 0 32rpx 32rpx;
		}

		&__button {
			margin: 84rpx 0 0;

			.button {
				height: 104rpx;
				background: #b3d3ff !important;
				border-radius: 52rpx;
				font-weight: 500;
				font-size: 34rpx;
				color: #ffffff;
				line-height: 104rpx;
				letter-spacing: 10rpx;
				text-align: center;
			}
		}

		&__password--forget {
			display: flex;
			font-size: 24rpx;
			align-items: center;
			margin: 32rpx;
			line-height: 40rpx;
		}

		&__usepassword {
			font-weight: 400;
			font-size: 28rpx;
			color: #2f80ed;
			line-height: 40rpx;
			text-align: center;
			margin-top: 33rpx;
		}

		&__others {
			margin-top: 26%;
			text-align: center;

			.login-button {
				padding: 0;
				margin: 0;
				border: none;
				background: transparent;
				width: 82rpx;
				height: 82rpx;
				line-height: 1;
				display: flex;
				justify-content: center;
				align-items: center;

				&::after {
					border: none;
				}
			}

			.wx_button {
				width: 82rpx;
				height: 82rpx;
				display: block;
			}

			&-label {
				font-weight: 400;
				font-size: 24rpx;
				color: #999999;
				line-height: 33rpx;
			}
		}

		.input_tel {
			width: 44rpx;
			height: 44rpx;
		}

		.input_code {
			width: 44rpx;
			height: 44rpx;
			margin: 0 16rpx 0 26rpx;
		}

		.verify {
			width: 220rpx;
			background: #b3d3ff;
			border-radius: 34rpx;
			padding: 14rpx 30rpx;
			font-weight: 400;
			font-size: 28rpx;
			color: #ffffff;
			line-height: 40rpx;
		}

		.verify--active {
			background: #2f80ed !important;
		}

		.verify::after {
			border: none;
		}

		.verify[disabled]:not([type]) {
			background: transparent;
			color: #333;
		}

		/* pages/index/index.wxss */

		.blue_link {
			color: #2f80ed;
		}
	}

	.login__others {
		margin-top: 26%;
		height: 177rpx;
		display: flex;
		justify-content: space-around;
		flex-direction: column;
		align-items: center;
	}
</style>